package com.jerei.store.service.impl;

import com.jerei.store.entity.Collect;
import com.jerei.store.entity.Product;
import com.jerei.store.mapper.CollectMapper;
import com.jerei.store.mapper.ProductMapper;
import com.jerei.store.service.ICollectService;
import com.jerei.store.service.ex.DeleteException;
import com.jerei.store.service.ex.InsertException;
import com.jerei.store.service.ex.SelectException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CollectServiceImpl implements ICollectService {

    @Autowired
    private CollectMapper collectMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public void addCollect(Integer uid, Integer pid,String username) {

        //判断数据库中是否有该商品
        Collect c=collectMapper.selectByPid(pid);
        if(c!=null){
            throw new InsertException("加入失败！该商品已存在");
        }

        Product product=productMapper.findById(pid);
        if(product==null){
            throw new SelectException("加入收藏失败，未找到该商品");
        }

        Collect collect=new Collect();
        collect.setPid(pid);
        collect.setUid(uid);
        collect.setImage(product.getImage());
        collect.setPrice(product.getPrice());
        collect.setTitle(product.getTitle());
        collect.setCreatedUser(username);
        Date date=new Date();
        collect.setCreatedTime(date);
        collect.setModifiedTime(date);
        collect.setModifiedUser(username);
        Integer rows=collectMapper.insertC(collect);
        if(rows!=1){
            throw new InsertException("加入收藏失败，发生未知错误");
        }


    }

    @Override
    public List<Collect> showCollect(Integer uid, Integer num) {
        if(num<1){
            throw new SelectException("页面下标错误，请重新尝试");
        }
        Integer limit=(num-1)*12;

        List<Collect> list= collectMapper.selectByUid(uid,limit);


        return list;
    }

    @Override
    public Integer count(Integer uid) {
        Integer num= collectMapper.selectNumByUid(uid);
        return num;
    }

    @Override
    public void delCollect(Integer uid, Integer pid) {

        Integer rows=collectMapper.deleteByPid(pid,uid);

//        if(rows!=1){
//            throw new DeleteException("取消收藏失败，发生未知错误");
//        }

    }
}
